#include <xc.h>
#include "MyCan.h"
#include "Config.h"
#include "Serial.h"
#include "libpic30.h"
#include "TemperatureStuff.h"
#include "Timer.h"
#include "SerialStateMachine.h"
#include "userConfig.h"
#include "CanMessage.h"
#include "leds.h"

void InitializeClock()
{
#ifndef USE_CRYSTAL
    //setup for FRC tuned up to ~8Mhz
    __builtin_write_OSCCONH(0b01110111);
    __builtin_write_OSCCONL(0b00000001);

    while(!OSCCONbits.LOCK)
        __builtin_nop();
#endif
}


int main(void)
{
   InitializeClock();

   OW_PIN_DIRECTION = OUTPUT;
   OW_WRITE_PIN = LOW;

   InitSerialStateMachine();
   InitializeUserConfig();
   InitializeTemperatureStuff();
   initEUSART();
   InitializeCAN();
   InitializeTimer();

   PutString("Hello World");				// Display Welocme Message on Terminal.

    initLEDs();
    TRISBbits.TRISB0 = 1;
    TRISBbits.TRISB1 = 1;
    ADPCFGbits.PCFG0 = 1;
    ADPCFGbits.PCFG1 = 1;
    while(1)
    {
        if(HasCANMessage())
        {
            CANMessage message;
            GetCANMessage(&message);
//            PutString("I got a message \r");
//            PrintCANMessage(&message);

            if(DoesIDMatchMessageBase_IgnoreSA(message.ID, TEMPERATURE_STATUS_MESSAGE_BASE))
            {
                TS_HandleExternalTemperatureMessageNew(&message);
            }
        }

        TS_ProcessMainLoop();
       while(HasData())
       {
           ProcessCharacter(Getchar());
       }

    }

} // END OF MAIN

